package org.demo.base.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {
	private static String token;

	public static String getToken() {
		return token;
	}

	@Value("${hcweb.token}")
	public void setToken(String token) {
		AuthInterceptor.token = token;
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws IOException {
		String staffid = req.getHeader(HcConstants.ReqHeader.STAFFID);
		String staffname = req.getHeader(HcConstants.ReqHeader.STAFFNAME);
		String timestamp = req.getHeader(HcConstants.ReqHeader.TIMESTAMP);
		String signature = req.getHeader(HcConstants.ReqHeader.SIGNATURE);
		String xRioSeq = req.getHeader(HcConstants.ReqHeader.X_RIO_SEQ);
		String xExtData = req.getHeader(HcConstants.ReqHeader.X_EXT_DATA);

		// 获取头部信息
		if (StringUtils.isBlank(staffid) || StringUtils.isBlank(staffname) || StringUtils.isBlank(timestamp)
				|| StringUtils.isBlank(signature)) {
			res.setStatus(HttpStatus.OK.value());
			res.getWriter().print("invalid request header");
			return false;
		}

		// 时间宽容度
		Long expire = (long) 60 * 30;
		Long now = System.currentTimeMillis() / 1000;
		Long timeLong = null;
		try {
			timeLong = Long.valueOf(timestamp);
		} catch (Exception e) {
			res.setStatus(HttpStatus.OK.value());
			res.getWriter().print("invalid timestamp header");
			return false;
		}

		if (now - timeLong > expire) {
			res.setStatus(HttpStatus.OK.value());
			res.getWriter().print("RIO 请求已过期，请检查服务器时间和时区是否正确；rio时间戳:" + timestamp + ";服务器时间戳：" + now);
			return false;
		}

		String source = String.format("%s%s%s,%s,%s,%s%s", timestamp, token, xRioSeq, staffid, staffname, xExtData,
				timestamp);

		// 与头部信息中的签名对比
		if (!SHA256Util.getSHA256StrJava(source).toUpperCase().equals(signature.toUpperCase())) {
			res.setStatus(HttpStatus.OK.value());
			res.getWriter().print("invalid signature");
			return false;
		}

		if (!org.apache.commons.lang3.StringUtils.isNumeric(staffid)) {
			res.setStatus(HttpStatus.OK.value());
			res.getWriter().print("AuthInterceptor invalid staffid " + staffid);
			return false;
		}

		LogUtil.info(AuthInterceptor.class, "PV", String.format("staffid:%s engname:%s", staffid, staffname));

//		req.getSession().setAttribute(HCAuthService.C_AUTH_STAFF_ID, staffid);// session失效时间
		return true;
	}
}
